<template>
  <div class="progress-bar" ref="progressBar" @click="short">
    <div class="bar-inner">
      <div class="progress" ref="progress"></div>
      <div
        class="progress-btn-wrapper"
        @touchstart.prevent="progressTouchStrat"
        @touchmove.prevent="progressTouchMove"
        @touchend.prevent="progressTouchEnd"
        ref="progressBtn"
      >
        <div class="progress-btn"></div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      touch: {
        initmove: false
      }
    }
  },
  props: {
    precent: {
      type: Number,
      default: 0
    }
  },
  watch: {
    precent(newPrecent) {
      if (this.touch.initmove) {
        return
      }
      const progerssWidth = newPrecent * this.$refs.progressBar.offsetWidth
      this._setProgressWidth(progerssWidth)
    }
  },
  methods: {
    _setProgressWidth(progerssWidth) {
      this.$refs.progress.style.width = `${progerssWidth}px`
      this.$refs.progressBtn.style.transform = `translateX(${progerssWidth - 8}px)`
    },
    short(e) {
      this._setProgressWidth(e.clientX - 80)
      this.submitWidth()
    },
    progressTouchStrat(e) {
      this.touch.initmove = true
      this.touch.startX = e.touches[0].pageX
      this.touch.left = this.$refs.progress.clientWidth
    },
    progressTouchMove(e) {
      if (!this.touch.initmove) {
        return
      }
      const moveX = e.touches[0].pageX - this.touch.startX
      const progerssWidth = Math.min(
        this.$refs.progressBar.offsetWidth,
        Math.max(0, moveX + this.touch.left)
      )

      this._setProgressWidth(progerssWidth)
    },
    submitWidth() {
      const width = this.$refs.progress.clientWidth
      const precent = width / this.$refs.progressBar.offsetWidth
      this.$emit('touchMove', precent)
    },
    progressTouchEnd() {
      this.touch.initmove = false
      this.submitWidth()
    }
  }
}
</script>
<style scoped lang="stylus" rel="stylesheet/stylus">
@import '~common/stylus/variable';

.progress-bar {
  height: 30px;

  .bar-inner {
    position: relative;
    top: 13px;
    height: 4px;
    background: rgba(0, 0, 0, 0.3);

    .progress {
      position: absolute;
      height: 100%;
      background: $color-theme;
    }

    .progress-btn-wrapper {
      position: absolute;
      left: -8px;
      top: -13px;
      width: 30px;
      height: 30px;

      .progress-btn {
        position: relative;
        top: 7px;
        left: 7px;
        box-sizing: border-box;
        width: 16px;
        height: 16px;
        border: 3px solid $color-text;
        border-radius: 50%;
        background: $color-theme;
      }
    }
  }
}
</style>